package com.example.web;

import com.example.daoman.User;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.Message;
import com.example.utils.RandomStringUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.apache.shiro.SecurityUtils.getSubject;

//用户登录 注册 忘记密码
@RestController
public class UserLogin {


    @Autowired
    private UserServiceImpl userService;

    //    用户登录
    @RequestMapping("/login")
    public Message login(@RequestBody User user) {
        try {
            String name = user.getName();
            String password = user.getPassword();
            UsernamePasswordToken upToken = new UsernamePasswordToken(name, password);
            Subject subject = getSubject();
            subject.login(upToken);
            String id = "";
            if (subject.getSession() != null) {
                id = (String) subject.getSession().getId();
            }
            return Message.out(200, "登录成功", id);
        } catch (Exception e) {
            return Message.out(400, "登录失败", "");
        }
    }


    //随机验证码
    @RequestMapping("/random")
    public String getRandom() {
        return RandomStringUtils.getRandomString(5);
    }

    //    忘记密码
    @RequestMapping("/forget")
    public Message forget(@RequestBody User user) {
        return userService.forget(user);
    }

}
